package com.qwc.blog.security.handler;

import com.qwc.blog.common.constant.CommonConstant;
import com.qwc.blog.security.service.LoginService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Objects;

/**
 * @author qwc
 * @Date 2021/10/15 10:08
 * 登出成功处理
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class MyLogoutSuccessHandler implements LogoutSuccessHandler {

    @Autowired
    private LoginService loginService;
    @Autowired
    private CaffeineCacheManager cacheManager;

    @Override
    public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        Cache cache = cacheManager.getCache(CommonConstant.USER_CACHE);
        if (Objects.nonNull(cache)) {
            cache.evictIfPresent(loginService.getLoginUser(httpServletRequest).getUsername());
        }
        httpServletResponse.setStatus(HttpStatus.OK.value());
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.getWriter().print("退出成功");
    }
}
